# -*- coding: utf-8 -*-
'''
Created on 2009-10-9

@author: ray
'''
from PyQt4 import QtCore, QtGui
from Gui.UI_IPmsgWindow import Ui_MainWindow
from Gui.UI_SessionDlg import Ui_Session_Dialog
from ipmsg.ipmsg import *
from sre_constants import CHCODES

class SessionDlg(QtGui.QDialog, Ui_Session_Dialog):
    
    def __init__(self, host, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.parent = parent
        self.host = host
        self.recvFiles = []
        self.sendFiles = []
        self.fileIcon = QtGui.QIcon("icon/file.ico")
        self.folderIcon = QtGui.QIcon("icon/folder.ico")
        self.setupUi(self)
        self.setWindowIcon(parent.icon)
        self.setWindowTitle("%s at %s(%s)" %(host.userName, host.hostName, host.addr))
        self.connect(self.send_Button, QtCore.SIGNAL("clicked()"), self.sendButtonClicked)
        self.connect(self.close_Button, QtCore.SIGNAL("clicked()"), self.closeButtonClicked)
        self.connect(self.recv_Button, QtCore.SIGNAL("clicked()"), self.recvButtonClicked)
        self.connect(self.addFile_Button, QtCore.SIGNAL("clicked()"), self.addFileButtonClicked)
        self.connect(self.addFolder_Button, QtCore.SIGNAL("clicked()"), self.addFolderButtonClicked)
        self.parent.informRecvPercent = self.informRecvPercent
        self.parent.informRecvDone = self.informRecvDone
        self.parent.informSendDone = self.informSendDone
        
    def closeEvent(self, e):
        self.parent.openedSessions.remove(self)
        e.accept()
    
    def addFileButtonClicked(self):
        fs = QtGui.QFileDialog.getOpenFileNames(self)
        for f in fs:
            self.sendFiles.append(unicode(f).encode("gb2312"))
        
    def addFolderButtonClicked(self):
        p = QtGui.QFileDialog.getExistingDirectory(self)
        if p != "":
            self.sendFiles.append(unicode(p).encode("gb2312"))
        
    def sendButtonClicked(self):
        '''This way of getting text won't work with multilines, don't forget to
        correct it!!! ''' 
        if self.sendFiles != []:
            lst = "\n".join([f.decode("gb2312") for f in self.sendFiles])
            chc = QtGui.QMessageBox.question(self,"Please confirm!", "Are you sure to send these files\n%s" %lst, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel)
            if chc != QtGui.QMessageBox.Ok:
                return
        msg = self.input_Text.toPlainText()
        self.session_Text.append(u"you %s\r\n  %s\r\n" %(time.asctime(), msg))
        self.input_Text.clear()
        isSeal = self.seal_checkBox.isChecked()
        isLock = self.lock_checkBox.isChecked()
        self.parent.sendMsg(self.host, unicode(msg).encode("gb2312"), isSeal, isLock, self.sendFiles)
        self.sendFiles = []
    
    def closeButtonClicked(self):
        self.close()
    
    def recvButtonClicked(self):
        if self.recvFiles != []:
            msg, f = self.recvFiles.pop(0)
            p = QtGui.QFileDialog.getExistingDirectory(self, "Choose a saving location for %s." %f.name.decode("gb2312"))
            if p != "":
                RecvFilesThread(self.parent, msg, [f], unicode(p).encode("gb2312")).start()
            else:
                self.recvFiles.insert(0, (msg, f))
    
    def newMsgArr(self, msg, files):
        text = QtCore.QString("%s %s\r\n  %s\r\n" %(self.host.userName, time.asctime(), msg.msg.decode("gb2312")))
        self.session_Text.append(text)
        self.session_Text.textCursor().movePosition(QtGui.QTextCursor.End)
        for f in files:
            title = ""
            self.recvFiles.append((msg, f))
            title = "|".join((title, f.name.decode("gb2312")))
            QtGui.QMessageBox.information(self, "Attachment", "There is an attachment in this message!")
            self.recv_Button.setText(title)
            
    def informRecvPercent(self, name, rlen, size):
        per = rlen*100/size
        self.status_Label.setText("%s %d%%" %(name.decode("gb2312"), per))
    
    def informRecvDone(self):
        self.status_Label.setText("transfer is done.")
        title = "Receive File/Folder"
        for f in self.recvFiles:
            title = ",".join((title, f[1].name))
        self.recv_Button.setText(title)
    
    def informSendDone(self, name):
        self.status_Label.setText("send %s complete" %name.decode("gb2312"))
    
class IPmsgGui(Ui_MainWindow, IPMsg, QtGui.QMainWindow):


    def __init__(self, parent=None):
        IPMsg.__init__(self, ("", IPMSG_DEFAULT_PORT))
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.buddylist = self.buddyGroups.topLevelItem(0)
        self.blacklist = self.buddyGroups.topLevelItem(1)
        self.connect(self.buddyGroups, QtCore.SIGNAL("doubleClicked(QModelIndex)"), self.treeItemDoubleClicked)
        self.connect(self, QtCore.SIGNAL("MsgArrives"), self.MsgSendMsgEx)
        self.icon = QtGui.QIcon("icon/ipmsg.ico")
        self.msgRevSound = QtGui.QSound("sound/msg.wav")
        self.globalSound = QtGui.QSound("sound/Global.wav")
        self.setWindowIcon(self.icon)
        self.eventLoop()
        self.broadcastOnline()
        self.openedSessions = []
        
    def treeItemDoubleClicked(self, index):
        ipaddr = self.buddylist.child(index.row()).toolTip(0)
        h = self.hostmgr.getByAddr(ipaddr)
        print h
        if h and not self.getOpenedSeesion(h):
            d = SessionDlg(h, self)
            self.openedSessions.append(d)
            d.show()
            
    def getOpenedSeesion(self, host):
        for s in self.openedSessions:
                if host == s.host:
                    print host, s.host
                    return s
        return None
        
    def MsgAnsEntry(self, msg):
        IPMsg.MsgAnsEntry(self, msg)
        item = QtGui.QTreeWidgetItem(self.buddylist)
        item.setText(0, msg.host.userName)
        item.setToolTip(0, msg.host.addr)
        item.setIcon(0, self.icon)
        self.globalSound.play()
    
    def MsgSendMsgEx(self, msg):
        files = IPMsg.MsgSendMsg(self, msg)
        d = self.getOpenedSeesion(msg.host)
        if not d:
            d = SessionDlg(msg.host, self)
            self.openedSessions.append(d)
            d.show()
        d.newMsgArr(msg, files)
        
    def MsgSendMsg(self, msg):
        ''' Because this function will be called in another thread, 
        Qt won't be able to set the newly-created dialog's parent, 
        so we should do this by sending Qt signals'''
        self.emit(QtCore.SIGNAL("MsgArrives"), msg)
        self.msgRevSound.play()
        
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    gui = IPmsgGui()
    gui.show()
    sys.exit(app.exec_())
    exit(-1)
